<template>
  <div id="app">
    <h1>购物车</h1>
    <ul>
      <li v-for="(v,i) of fruits" :key="i">
        {{v.name}}
        单价：{{v.price}}
        <counter :qu="v.qu" :index="i" @add="add" @sub="sub"></counter>
      </li> 
    </ul>
    <h2>总价格：{{totalprice}}</h2>
  </div>
</template>

<script>
import Counter from "./Counter";
export default {
  components: { Counter, },
  //   name: "App",
  data() {
    return {
      fruits: [
        { name: "苹果", price: 2.5, qu: 0 },
        { name: "香蕉", price: 3.5, qu: 0 },
        { name: "鸭梨", price: 3, qu: 0 }
      ],
    };
  },
  methods: {
    add(index) {
      this.fruits[index].qu++;
    },
    sub(index) {
      if (this.fruits[index].qu> 0) {
        this.fruits[index].qu--;
      }

    }
  },
  computed:{
    totalprice:function(){
      let result = 0;
      for (let  i=0; i<this.fruits.length; i++){
        result+=this.fruits[i].price *this.fruits[i].qu
      }
      return result
    },
    

  }
};
</script>

<style>
</style> 